﻿using AutoMapper;
using Basic.Traceability.Domain;
using Basic.Traceability.ErrorCode;
using Basic.Traceability.Host.Api.Read.Application.Command.User;
using Basic.Traceability.Host.Api.Read.Dto;
using Basic.Traceability.Intrestructrue.Base;
using MD5Hash;
using MediatR;

namespace Basic.Traceability.Host.Api.Read.Application.Handler.User
{
    public class LoginHandler : IRequestHandler<LoginCommand, APIResult<UserDto>>
    {
        private readonly IBaseRepository<UserModel> userRepositority;
        private readonly IMapper mapper;
        private readonly ILogger<LoginHandler> logger;

        public LoginHandler(IBaseRepository<UserModel> userRepositority, IMapper mapper, ILogger<LoginHandler> logger)
        {
            this.userRepositority = userRepositority;
            this.mapper = mapper;
            this.logger = logger;
        }


        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<APIResult<UserDto>> Handle(LoginCommand request, CancellationToken cancellationToken)
        {
            APIResult<UserDto> res = new APIResult<UserDto>();
            var pwd = request.Password.GetMD5();
            var model = userRepositority.GetALL().FirstOrDefault(x => x.UserName == request.UserName && x.Password == pwd);
            if(model==null)
            {
                res.Code = APIEnums.Fail;
                res.Msg = "用户名或密码错误";
                logger.LogError("用户名或密码错误");
                return Task.FromResult(res);

            }
            res.Data=mapper.Map<UserDto>(model);
            res.Code = APIEnums.Success;
            res.Msg = "登录成功";
            logger.LogInformation("登录成功");
            return Task.FromResult(res);
        }
    }
}
